package com.xuebusi.toutiao.admin.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuebusi.toutiao.admin.api.common.exception.CustomException;
import com.xuebusi.toutiao.admin.api.common.result.ApiResult;
import com.xuebusi.toutiao.admin.api.user.dao.CollectDao;
import com.xuebusi.toutiao.admin.api.user.entity.CollectEntity;
import com.xuebusi.toutiao.admin.api.user.entity.SourceEntity;
import com.xuebusi.toutiao.admin.api.user.service.CollectService;
import com.xuebusi.toutiao.admin.api.user.service.SourceService;
import com.xuebusi.toutiao.admin.api.user.vo.CollectRVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("collectService")
public class CollectServiceImpl extends ServiceImpl<CollectDao, CollectEntity> implements CollectService {
    @Resource
    private SourceService sourceService;

    /**
     * 收藏
     *
     * @param collectEntity
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<CollectRVO>> collect(CollectEntity collectEntity) {
        SourceEntity sourceEntity = sourceService.getById(collectEntity.getSourceId());
        if (sourceEntity == null) {
            throw new CustomException("资源不存在", 401);
        }
        CollectEntity query = this.getOne(new QueryWrapper<CollectEntity>()
                .eq("user_id", collectEntity.getUserId())
                .eq("source_id", collectEntity.getSourceId())
                .eq("type", collectEntity.getType()));
        if (query != null) {
            throw new CustomException("你已经收藏过了", 401);
        }
        this.save(collectEntity);
        CollectRVO collectRVO = new CollectRVO(collectEntity.getSourceId(), true);
        return new ResponseEntity(ApiResult.ok(collectRVO), HttpStatus.CREATED);
    }

    /**
     * 取消收藏
     *
     * @param userId   用户id
     * @param sourceId 资源id
     * @param type     资源类型
     * @return
     */
    @Override
    public ResponseEntity<ApiResult<CollectRVO>> cancel(Integer userId, Integer sourceId, int type) {
        this.remove(new QueryWrapper<CollectEntity>()
                .eq("user_id", userId)
                .eq("source_id", sourceId)
                .eq("type", type));
        CollectRVO collectRVO = new CollectRVO(sourceId, false);
        return new ResponseEntity(ApiResult.ok(collectRVO), HttpStatus.CREATED);
    }
}
